package com.hnld.transform.handler.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hnld.transform.cosntant.TransformConstant;
import com.hnld.transform.entity.LBIRoute;
import com.hnld.transform.entity.Parameter;
import com.hnld.transform.handler.IOtherFileHandler;
import com.hnld.transform.util.CSVFileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

public class OtherLBIFileHandler implements IOtherFileHandler {
    private static List<String> targets= Lists.newArrayList();
    private static Map<String,String> sourceMap= Maps.newHashMap();
    private static String routePath="/路面图像/";
    static {
        //
        targets.add("DR");
        targets.add("IRI");
        targets.add("LBI");
        targets.add("RIFile");
        //对应的源文件夹目录
        sourceMap.put("DR","/路面景象/识别结果/");
        sourceMap.put("IRI","/平整度数据/IRI/");
        sourceMap.put("LBI","/LBI/");
        sourceMap.put("RIFile","/平整度数据/RIFile/");
    }

    @Override
    public String getType() {
        return "LBI";
    }


    @Override
    public void handleFileType(List<File> files, String targetDir, String area, String areaRouteCode, Parameter parameter, Map<String, Integer> twoDirectionsMap) {
        System.out.println("处理区县【" + area + "】的路线【" + areaRouteCode + "】非图像类LBI数据");
        //IRI文件在区县的LBI文件夹下
        String LBIPath = parameter.getBaseSourcePath() + area + "/" + sourceMap.get(getType());
        //List<File> lbiFiles = FileUtil.loopFiles(LBIPath);
        String routeCode = areaRouteCode.substring(0, areaRouteCode.length() - 1);
        if (!twoDirectionsMap.isEmpty()) {
            Integer integer = Optional.ofNullable(twoDirectionsMap.get(routeCode)).orElse(0);
            //是否有两个方向
            if (integer > 1) {//有两个方向判定
                files = files.stream().filter(f -> f.getName().startsWith(areaRouteCode)).collect(Collectors.toList());//精确
            } else {
                files = files.stream().filter(f -> f.getName().startsWith(routeCode)).collect(Collectors.toList());//模糊
            }
        }
        List<File> fileList = files;
        if (CollectionUtil.isEmpty(fileList)){
            System.out.println("未找到区县【"+area+"】的路线【"+areaRouteCode+"】非图像类LBI数据");
            TransformConstant.LBI_ROUTE.add(areaRouteCode);
            return;
        }
        for (File f:fileList){
           //文件名调整 C00A431102A-LBI-0.000-20230729081204.csv 转换为: C00A431102A-LBI-0.000-20230714105000.txt
            String fileName = areaRouteCode.concat(f.getName().substring(f.getName().indexOf("-"), f.getName().length()));
            fileName = fileName.replace(".csv", ".txt");
            //写文件
            writeCSVData(f,targetDir+"/"+fileName);
        }

    }
    private static void writeCSVData(File file, String targetPath){
        List<String> writeContent = new ArrayList<>();
        List<LBIRoute> lbiRoutes = CSVFileUtils.readCSVData(file.getAbsolutePath(), LBIRoute.class,false);
        List<String> titleList = CSVFileUtils.getTitleList(LBIRoute.class, TransformConstant.excludeTitle, "有效性", 3);
        String titleContent = String.join(",", titleList);
        writeContent.add(titleContent);
        lbiRoutes.forEach(data -> {
            String stake = data.getStake();
            if (StringUtils.isBlank(stake)){
                return;
            }
            //替换字符
            stake = replaceCharacters(stake);

            //判断是否为数字
            if (NumberUtil.isNumber(stake)) {
                //起点桩号(km),经度,纬度,有效性,桩号数据要除以1000
                BigDecimal state = new BigDecimal(stake).divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
                String content = "";
                //state + "," + data.getLongitude() + "," + data.getLatitude() + "," + data.getValidity()
                if (NumberUtil.isNumber(data.getLongitude()) && contain(data.getLongitude()) ||
                        NumberUtil.isNumber(data.getLatitude()) && contain(data.getLatitude())) {
                    content = state + "," + data.getLongitude() + "," + data.getLatitude() + "," ;//无效
                } else {
                    content = state + "," + data.getLongitude() + "," + data.getLatitude() + "," ;
                }
                writeContent.add(content);
            } else {
                String sourceFilePath = FileUtil.getAbsolutePath(file);
                throw new RuntimeException("源文件数据数据格式错误。源文件路径：" + sourceFilePath);
            }
        });
        //写入文件
        FileUtil.writeLines(writeContent,targetPath, Charset.defaultCharset());
    }

    //替换字符
    public static String replaceCharacters(String sourceStr) {
        String targetStr = null;
        //替换 +
        if (sourceStr.contains("+")) {
            sourceStr = sourceStr.replace("+", "");
        }

        //K0+487 替换成0.487
        if (sourceStr.contains("K") || sourceStr.contains("k")) {
            sourceStr = sourceStr.replace("K", "").replace("k", "");
        }
        targetStr = sourceStr;
        return targetStr;
    }

    //包含
    public static boolean contain(String source) {
        List<String> list = Arrays.asList("0", "0.0", "0.00", "0.000", "0.0000", "0.000000");
        return list.contains(source);
    }

    public static void main(String[] args) {
        String str = "C00A431102A-LBI-0.000-20230729081204.csv";
        System.out.println(str.substring(str.indexOf("-"), str.length()));
    }

}
